<template>
  <a-modal
    :open="open"
    title="态势对象详情"
    width="800px"
    :footer="null"
    :maskClosable="true"
    @cancel="handleClose"
  >
    <div v-if="objectData" class="detail-container">
      <!-- 基础信息 -->
      <a-descriptions title="基础信息" bordered :column="2" size="small">
        <a-descriptions-item label="对象类型">
          <a-tag :color="getTypeColor(objectData.object_type)">
            {{ getTypeLabel(objectData.object_type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="装备类别">
          <a-tag color="blue" v-if="objectData.equipment_category">
            {{ getEquipmentCategoryLabel(objectData.equipment_category) }}
          </a-tag>
          <span v-else>-</span>
        </a-descriptions-item>
        <a-descriptions-item label="名称">{{ objectData.name }}</a-descriptions-item>
        <a-descriptions-item label="编码">{{ objectData.code || '-' }}</a-descriptions-item>
        <a-descriptions-item label="描述" :span="2">{{ objectData.description || '-' }}</a-descriptions-item>
        <a-descriptions-item label="型号">{{ objectData.model || '-' }}</a-descriptions-item>
        <a-descriptions-item label="所属单位">{{ objectData.organization || '-' }}</a-descriptions-item>
        <a-descriptions-item label="部署状态">
          <a-tag :color="getStatusColor(objectData.deployment_status)">
            {{ objectData.deployment_status || '未知' }}
          </a-tag>
        </a-descriptions-item>
      </a-descriptions>

      <!-- 类型特定字段 - 观测装备-卫星 -->
      <a-descriptions
        v-if="objectData.equipment_category === '卫星' && objectData.type_specific_data"
        title="类型特定字段 - 观测装备-卫星"
        bordered
        :column="2"
        size="small"
        style="margin-top: 16px"
      >
        <a-descriptions-item label="卫星名称">
          {{ objectData.type_specific_data.name || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="运行状态">
          <a-tag :color="objectData.type_specific_data.status === 'online' ? 'green' : 'red'">
            {{ objectData.type_specific_data.status || '-' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="是否激活">
          <a-tag :color="objectData.type_specific_data.active ? 'green' : 'default'">
            {{ objectData.type_specific_data.active ? '激活' : '未激活' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="轨道类型">
          {{ objectData.type_specific_data.orbit_type || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="轨道高度">
          {{ objectData.type_specific_data.altitude ? objectData.type_specific_data.altitude + ' km' : '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="轨道周期">
          {{ objectData.type_specific_data.orbit_period || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="覆盖范围">
          {{ objectData.type_specific_data.coverage ? objectData.type_specific_data.coverage.toLocaleString() + ' km²' : '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="重访周期">
          {{ objectData.type_specific_data.revisit_period || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="工作波段">
          {{ objectData.type_specific_data.band || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="带宽">
          {{ objectData.type_specific_data.bandwidth || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="电池电量">
          <a-progress
            :percent="parseInt(objectData.type_specific_data.battery) || 0"
            size="small"
            :status="parseInt(objectData.type_specific_data.battery) > 30 ? 'normal' : 'exception'"
          />
        </a-descriptions-item>
        <a-descriptions-item label="燃料剩余">
          <a-progress
            :percent="parseInt(objectData.type_specific_data.fuel) || 0"
            size="small"
            :status="parseInt(objectData.type_specific_data.fuel) > 30 ? 'normal' : 'exception'"
          />
        </a-descriptions-item>
        <a-descriptions-item label="当前位置" :span="2">
          {{ objectData.type_specific_data.current_position || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="载荷配置" :span="2">
          <div v-if="objectData.type_specific_data.payload && objectData.type_specific_data.payload.length > 0">
            <div v-for="(payload, index) in objectData.type_specific_data.payload" :key="index"
                 style="margin-bottom: 8px; padding: 8px; background: #f5f5f5; border-radius: 4px;">
              <div><strong>载荷 {{ index + 1 }}:</strong></div>
              <div>类型: {{ payload.type || '-' }}</div>
              <div>分辨率: {{ payload.resolution || '-' }}</div>
              <div>幅宽: {{ payload.swath || '-' }}</div>
            </div>
          </div>
          <span v-else>-</span>
        </a-descriptions-item>
      </a-descriptions>

      <!-- 其他类型特定数据 -->
      <a-descriptions
        v-else-if="objectData.type_specific_data && Object.keys(objectData.type_specific_data).length > 0"
        :title="`类型特定字段 - ${getTypeLabel(objectData.object_type)}-${objectData.equipment_category}`"
        bordered
        :column="2"
        size="small"
        style="margin-top: 16px"
      >
        <a-descriptions-item
          v-for="(value, key) in objectData.type_specific_data"
          :key="key"
          :label="formatFieldName(key)"
        >
          {{ formatFieldValue(value) }}
        </a-descriptions-item>
      </a-descriptions>

      <!-- 其他信息 -->
      <a-descriptions title="其他信息" bordered :column="1" size="small" style="margin-top: 16px">
        <a-descriptions-item label="感知能力详情">
          {{ objectData.perception_capability || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="通信能力详情">
          {{ objectData.communication_capability || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="适用场景">
          {{ objectData.applicable_scenarios || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="地理位置信息">
          {{ objectData.location || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="标签">
          <a-tag v-for="tag in (objectData.tags || [])" :key="tag" color="purple" style="margin-right: 8px">
            {{ tag }}
          </a-tag>
          <span v-if="!objectData.tags || objectData.tags.length === 0">-</span>
        </a-descriptions-item>
      </a-descriptions>

      <!-- 元数据 -->
      <a-descriptions title="元数据" bordered :column="2" size="small" style="margin-top: 16px">
        <a-descriptions-item label="创建时间">{{ formatDate(objectData.created_at) }}</a-descriptions-item>
        <a-descriptions-item label="更新时间">{{ formatDate(objectData.updated_at) }}</a-descriptions-item>
        <a-descriptions-item label="创建人">{{ objectData.created_by || '-' }}</a-descriptions-item>
        <a-descriptions-item label="更新人">{{ objectData.updated_by || '-' }}</a-descriptions-item>
      </a-descriptions>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { getEquipmentCategoryLabels } from '@/apis'
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  objectData: {
    type: Object,
    default: null
  },
  objectTypes: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:open'])

// 关闭弹窗
function handleClose() {
  emit('update:open', false)
}

// 装备类别标签映射（从后端获取）
const equipmentCategoryLabels = ref({})

// 获取类型标签
function getTypeLabel(type) {
  const found = props.objectTypes.find(t => t.value === type)
  return found ? found.label : type
}

// 获取装备类别中文标签
function getEquipmentCategoryLabel(value) {
  return equipmentCategoryLabels.value[value] || value
}

// 获取类型颜色
function getTypeColor(type) {
  const found = props.objectTypes.find(t => t.value === type)
  return found ? found.color : '#666'
}

// 获取状态颜色
function getStatusColor(status) {
  const colorMap = {
    '已部署': 'green',
    '待部署': 'orange',
    '维护中': 'blue',
    '退役': 'gray'
  }
  return colorMap[status] || 'default'
}

// 格式化字段名称
function formatFieldName(key) {
  const nameMap = {
    // 通用字段（新增）
    coordinates: '当前位置',
    importance: '重要程度',
    discovery_time: '发现时间',

    // 武器系统
    weapon_category: '武器类别',
    caliber: '口径(mm)',
    range: '射程(km)',
    warhead_type: '弹头类型',

    // 基础设施
    infrastructure_category: '设施类别',
    capacity: '容量',
    area: '占地面积(㎡)',
    altitude: '海拔(m)',
    runway_length: '跑道长度(m)',
    runway_width: '跑道宽度(m)',
    runway_count: '跑道数量',
    runway_surface: '跑道表面',
    usage_type: '使用性质',
    usage_time: '使用时间',
    berth_count: '泊位数量',
    max_vessel_tonnage: '最大停靠吨位',
    water_depth: '水深(m)',
    power_generation: '发电量(MW)',
    fuel_type: '燃料类型',
    discovery_time: '发现时间',
    exploitation_time: '开采时间',
    total_reserves: '总储量',
    annual_output: '年产量',
    oilfield_area: '油田面积',
    main_production_layer: '主产油层',
    station_type: '车站类型',
    platform_count: '站台数量',
    daily_trains: '日均列车班次',
    passenger_capacity: '日均客流量(人次)',
    freight_capacity: '货运能力(万吨/年)',
    discovery_time: '发现时间',
    exploitation_time: '开采时间',
    total_reserves: '总储量',
    annual_output: '年产量',
    oilfield_area: '油田面积',
    main_production_layer: '主产油层',

    // 海上目标（驱逐舰等）
    target_category: '目标类别',
    target_type: '目标类型',
    displacement: '排水量(吨)',
    length: '长度(m)',
    beam: '宽度(m)',
    draft: '吃水(m)',
    max_speed: '最高速度(节)',
    cruise_speed: '巡航速度(节)',
    endurance: '最大里程(海里)',
    crew_capacity: '人员数量',
    propulsion_type: '动力系统',
    armament: '武器系统',
    sensors: '雷达/传感器',
    home_port: '母港',
    imo_number: 'IMO编号',
    mmsi: 'MMSI编号',
    production_date: '生产日期',
    service_start_time: '服役时间',
    aircraft_capacity: '最大载机数量',
    aircraft_capacity_text: '载机数量描述',
    flight_deck_info: '飞行甲板信息',
    armament_text: '武器系统描述',

    // 观测装备
    vessel_category: '船只类别',
    sensor_category: '传感器类别',
    aircraft_category: '飞行器类别',
    vehicle_category: '车辆类别',
    equipment_category: '装备类别',
    detection_range: '探测距离(km)',
    frequency: '工作频率',
    resolution: '分辨率',
    launch_time: '发射时间',
    sensor_type: '传感器类型',
    spatial_resolution: '空间分辨率',
    spectral_bands: '光谱波段',
    swath_width: '幅宽(km)',
    revisit_time: '重访时间(天)',
    typical_usage: '典型用途',

    // 卫星专用字段
    name: '卫星名称',
    status: '运行状态',
    active: '是否激活',
    altitude: '轨道高度(km)',
    coverage: '覆盖范围(km²)',
    resolution: '分辨率(m)',
    orbit_type: '轨道类型',
    orbit_period: '轨道周期',
    payload: '载荷配置',
    band: '工作波段',
    bandwidth: '带宽',
    revisit_period: '重访周期',
    battery: '电池电量',
    fuel: '燃料剩余',
    current_position: '当前位置',

    // 陆上目标
    site_area: '占地面积(㎡)',
    building_area: '建筑面积(㎡)',
    main_function: '主要功能',
    construction_year: '建设年份'
  }
  return nameMap[key] || key
}

// 格式化字段值
function formatFieldValue(value) {
  if (value === null || value === undefined) return '-'

  // 处理数组类型（如传感器列表）
  if (Array.isArray(value)) {
    return value.join(', ')
  }

  // 处理对象类型（如武器系统）
  if (typeof value === 'object') {
    // 如果有description字段，优先显示
    if (value.description) {
      return value.description
    }
    // 如果有systems数组，显示为列表
    if (value.systems && Array.isArray(value.systems)) {
      return value.systems.join(', ')
    }
    // 否则显示JSON
    return JSON.stringify(value, null, 2)
  }

  // 处理重要程度字段
  if (value === 'general') return '一般'
  if (value === 'important') return '重要'

  // 处理日期时间字段
  if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
    return formatDate(value)
  }

  return value
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 初始化装备类别标签
onMounted(async () => {
  try {
    const response = await getEquipmentCategoryLabels()
    equipmentCategoryLabels.value = response
  } catch (error) {
    console.error('获取装备类别标签失败:', error)
  }
})
</script>

<style scoped>
.detail-container {
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.ant-descriptions-title) {
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 12px;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
